package com.example.sandbox.controller.notice;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class PayComponent {

    private final CloseableHttpClient httpClient;

    public PayComponent() {
        // 创建带有连接池的 HttpClient 实例
        this.httpClient = HttpClients.custom()
                .setMaxConnTotal(200)  // 设置最大连接数
                .setMaxConnPerRoute(200)  // 设置每个路由的最大连接数
                .build();
    }

    ScheduledThreadPoolExecutor scheduledThreadPoolExecutorTransfer =
            new ScheduledThreadPoolExecutor(Runtime.getRuntime().availableProcessors() * 2);

    public void doNotifyPay(Map<String, Object> noticeMap, String notifyUrl, String contentType) {
        scheduledThreadPoolExecutorTransfer.schedule(() -> {
            // 执行推送
            try {
                notifyPaymentPay(noticeMap, notifyUrl, contentType);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }, 1, TimeUnit.SECONDS);
    }

    public void notifyPaymentPay(Map<String, Object> noticeMap, String notifyUrl, String contentType) throws IOException {
        Map<String, Object> params = new HashMap<>(noticeMap);

        try {
            HttpPost request = new HttpPost(notifyUrl);
            String json = new ObjectMapper().writeValueAsString(params);
            StringEntity entity = new StringEntity(json);
            entity.setContentType(contentType);
            request.setEntity(entity);


            CloseableHttpResponse response = httpClient.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                log.error("Failed to notify payment. HTTP Status: {}", statusCode);
            }

        } catch (IOException e) {
            log.error("Error serializing JSON: {}", e.getMessage());
            throw e; // 重新抛出以便上层处理
        }
    }

}
